/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.glidebitmappoolsample.util;

import com.glidebitmappoolsample.Constants;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.ResourceManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

/**
 * 文件工具类
 *
 * @author renpengfei
 * @since 2021-03-12
 */
public final class FileUtils {
    private static HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP, 0x001, Constants.TAG);
    private static boolean isDelete;

    private FileUtils() {
    }

    /**
     * 复制文件到当前目录
     *
     * @param context
     * @param fileName
     * @return boolean
     */
    public static boolean copy2Memory(Context context, String fileName) {
        File cacheDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        try {
            if (!cacheDir.exists()) {
                boolean isMkdirs = cacheDir.mkdirs();
            }
            File outFile = new File(cacheDir, fileName);
            if (!outFile.exists()) {
                boolean isRes = outFile.createNewFile();
                if (!isRes) {
                    return false;
                }
            } else if (outFile.length() > (long) Constants.TEN) {
                return true;
            }
            InputStream inputStream = getInputStream(context, fileName);

            FileOutputStream fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[Constants.ONE_THOUSAND_AND_TWENTY_FOUR];
            int byteCount;
            while ((byteCount = inputStream.read(buffer)) != Constants.NEGATIVE_ONE) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            inputStream.close();
            fos.close();
            return true;
        } catch (IllegalArgumentException | IOException e) {
            HiLog.error(hiLogLabel, e.getMessage());
            return false;
        }
    }

    private static InputStream getInputStream(Context context, String fileName) {
        ResourceManager resourceManager = context.getResourceManager();
        RawFileEntry rawFileEntry = resourceManager.getRawFileEntry(
                String.format("resources/rawfile/%s".toLowerCase(Locale.ENGLISH), fileName));
        InputStream inputStream = null;
        try {
            inputStream = rawFileEntry.openRawFile();
        } catch (IOException e) {
            e.getMessage();
        }
        return inputStream;
    }

    /**
     * 获取文件名称
     *
     * @param filePath
     * @return String
     */
    public static String getFileName(String filePath) {
        return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
    }

    /**
     * 创建写入内容文件
     * 请注意一定要申请文件读写权限
     *
     * @param context
     * @param filePaths
     * @return String
     */
    public static String createInputFile(Context context, String... filePaths) {
        File file = new File(context.getExternalCacheDir(), "input.txt");
        StringBuilder content = new StringBuilder();
        for (String filePath : filePaths) {
            content.append("file ").append(FileUtils.getFileName(filePath)).append(System.lineSeparator());
        }
        if (!file.exists()) {
            String string = null;
            try {
                boolean isNewFile = file.createNewFile();
                RandomAccessFile raf = new RandomAccessFile(file, "rwd");
                raf.seek(file.length());
                raf.write(content.toString().getBytes(StandardCharsets.UTF_8));
                raf.close();
                return file.getCanonicalPath();
            } catch (IOException e) {
                e.getMessage();
                return string;
            }
        } else {
            isDelete = file.delete();
            return createInputFile(context, filePaths);
        }
    }
}
